import { getLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';

const initialState = {
  suggestion: [] as string[],
  historuKeyword: getLocalHistories(),
  resultData: {
    total_count: 0,
    page: 1,
    per_page: 10,
    results: [] as ResultType[],
  },
};

export type ResultType = {
  art_id: string;
  title: string;
  aut_id: string;
  aut_name: string;
  comm_count: number;
  pubdate: string;
  cover: {
    type: number;
    images: string[];
  };
  like_count: number;
  collect_count: number;
};
// 扩展类型
type ActionType =
  | { type: 'search/suggestion'; payload: string[] }
  | { type: 'search/keyword'; payload: string }
  | { type: 'search/clearkeyword' }
  | { type: 'search/saveResult'; payload: typeof initialState.resultData }
  | { type: 'search/saveResultsList'; payload: typeof initialState.resultData };

export default function searchReducer(
  state = initialState,
  actions: ActionType
): typeof initialState {
  switch (actions.type) {
    case 'search/suggestion':
      return {
        ...state,
        // 处理脏数据 即后台没有数据时会返回一个null项 将它去掉  !! === Boolean() 强制转Boolean
        suggestion: actions.payload.filter((item) => !!item),
      };
    case 'search/keyword':
      return {
        ...state,
        historuKeyword: uniq([...state.historuKeyword, actions.payload]).slice(0, 10), // lodash方式去重
        // historuKeyword: [...(new Set([...state.historuKeyword, actions.payload]) as any)], // Set方式去重
      };
    case 'search/clearkeyword':
      return {
        ...state,
        historuKeyword: [],
      };
    // 点击搜索保存一次
    case 'search/saveResult':
      return {
        ...state,
        resultData: {
          total_count: actions.payload.total_count,
          page: actions.payload.page,
          per_page: actions.payload.per_page,
          results: actions.payload.results || [],
        },
      };
    // 滚动是更新保存
    case 'search/saveResultsList':
      return {
        ...state,
        resultData: {
          total_count: actions.payload.total_count,
          page: actions.payload.page,
          per_page: actions.payload.per_page,
          results: [...state.resultData.results, ...actions.payload.results],
        },
      };
    default:
      return state;
  }
}
